package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("菜品添加成功");
    }

    //分页查询菜品信息
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page,Integer pageSize,String name){
        //创建分页对象
        Page<Dish> pageInfo1 = new Page<>(page,pageSize);
        //设置条件构造器
        QueryWrapper<Dish>  queryWrapper = new QueryWrapper<>();
        //添加过滤条件 判断如果name不为空 那么将传过来的name数据赋值给变量name
        queryWrapper.like(name != null , "name",name );
        //添加排序条件 根据修改时间进行排序
        queryWrapper.orderByDesc("update_time");
        //执行分页查询
        dishService.page(pageInfo1,queryWrapper);
        //开始进行对象拷贝
        Page<DishDto> pageInfo2 = new Page<>(page,pageSize);
        //创建DishDto对象集合 用来存储DishDto数据
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : pageInfo1.getRecords()) {
            DishDto dishDto = new DishDto();
            //将dish数据copy到dishDto内
            BeanUtils.copyProperties(dish,dishDto);
            //根据dish.getCategoryId()菜品分类id查询分类对象
            Category category = categoryService.getById(dish.getCategoryId());
            //设置分类名称 根据category对象 拿到其分类名称 赋值给dishDto对象
            if(category != null){
                dishDto.setCategoryName(category.getName());
                //将dishDto添加到集合中
                dishDtoList.add(dishDto);
            }

        }
        //将dishDtoList集合封装到pageInfo2中
        pageInfo2.setRecords(dishDtoList);
        //拷贝第二部分数据   pageInfo2已经有了records数据 所以不用拷贝这一部分数据
        BeanUtils.copyProperties(pageInfo1,pageInfo2,"records");
         return R.success(pageInfo2);
    }

    //根据id查询菜品信息和对应的口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改提交的保存按钮
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据  删除修改的菜品分类
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);
        return  R.success("修改成功");
    }

    //删除菜品
    @DeleteMapping
    public R<String> delete(Long []  ids){
        dishService.deleteWithFlavor(ids);
        return  R.success("删除成功");
    }

    //停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,Long [] ids){
        dishService.updateStatus(status,ids);
        return R.success("状态修改成功");
    }

    //根据分类查询菜品 在添加套餐信息内查询菜品信息
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //动态构造key
        String key = "dish_"+dish.getCategoryId();
        //从redis中获取缓存资源
        List<DishDto>  dishDtoList1 = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList1!=null){
            //查询数据库如果有缓存直接返回
            return R.success(dishDtoList1);
        }

        //构造条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish1 : list) {
            //创建一个dishDto用来装数据
            DishDto dishDto = new DishDto();
            //拷贝基本数据
            BeanUtils.copyProperties(dish1,dishDto);
            //创建条件构造器 用来获取口味信息
            QueryWrapper<DishFlavor> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dish_id",dish1.getId());
            //将口味信息装入dishDto
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            //将dishDto添加到集合当中
            dishDtoList.add(dishDto);
        }
        //redis数据库无缓存  添加缓存 信息到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
